package trungsi.gea.photos.dao;

import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.springframework.stereotype.Repository;

import trungsi.gea.photos.domain.Folder;

@Repository
public class FolderDao extends GenericsDaoImpl<String, Folder> {

	public Folder findByName(final String folderName) {
		return getJdoTemplate().execute(new JdoCallback<Folder>() {
			@Override
			public Folder doWithPersistenceManager(PersistenceManager pm) {
				Query query = pm.newQuery(Folder.class);
				query.setFilter("name == folderName");
				query.declareParameters("String folderName");
				query.setUnique(true);
				return (Folder) query.execute(folderName);
			}});
	}

	@SuppressWarnings("unchecked")
	public List<Folder> findAll(final Date before, final int limit) {
		return getJdoTemplate().execute(new JdoCallback<List<Folder>>() {
			@Override
			public List<Folder> doWithPersistenceManager(PersistenceManager pm) {
				Query query = pm.newQuery(Folder.class);
				query.setFilter("createdDate < adate");
				query.declareParameters("java.util.Date adate");
				query.setOrdering("createdDate desc");
				query.setRange(0, limit);
				return (List<Folder>) query.execute(before);
			}});
	}

	@SuppressWarnings("unchecked")
	public List<Folder> findAll(final int limit) {
		return getJdoTemplate().execute(new JdoCallback<List<Folder>>() {
			@Override
			public List<Folder> doWithPersistenceManager(PersistenceManager pm) {
				Query query = pm.newQuery(Folder.class);
				query.setOrdering("createdDate desc");
				query.setRange(0, limit);
				return (List<Folder>) query.execute();
			}});
	}

	public int countAll() {
		return getJdoTemplate().execute(new JdoCallback<Integer>() {
			@Override
			public Integer doWithPersistenceManager(PersistenceManager pm) {
				Query query = pm.newQuery("select count(this) from " + Folder.class.getName());
				
				return (Integer) query.execute();
			}});
	}
	
}
